package com.videoaggre.zcl.utils

import android.content.Context
import android.util.DisplayMetrics
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexboxLayoutManager

class FullyFlexboxLayoutManager(
    context: Context,
    private val canScrollVertically: Boolean = false,
    private val canScrollHorizontally: Boolean = false
) : FlexboxLayoutManager(context) {
    override fun canScrollVertically() = canScrollVertically
    override fun canScrollHorizontally() = canScrollHorizontally
}

class FullyGridLayoutManager(
    context: Context?,
    spanCount: Int,
    private val canScrollVertically: Boolean = false,
    private val canScrollHorizontally: Boolean = false
) : GridLayoutManager(context, spanCount) {
    override fun canScrollVertically() = canScrollVertically
    override fun canScrollHorizontally() = canScrollHorizontally
}

class FullyLinearLayoutManager(
    context: Context?,
    orientation: Int = RecyclerView.VERTICAL,
    reverseLayout: Boolean = false,
    private val canScrollVertically: Boolean = false,
    private val canScrollHorizontally: Boolean = false
) : LinearLayoutManager(context, orientation, reverseLayout) {
    override fun canScrollVertically() = canScrollVertically
    override fun canScrollHorizontally() = canScrollHorizontally
}

class CenterLayoutManager(context: Context?, orientation: Int = VERTICAL, reverseLayout: Boolean = false) : LinearLayoutManager(context, orientation, reverseLayout) {
    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?, position: Int) {
        val smoothScroller: RecyclerView.SmoothScroller = CenterSmoothScroller(recyclerView.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private class CenterSmoothScroller(context: Context?) : LinearSmoothScroller(context) {
        override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int {
            return boxStart + (boxEnd - boxStart) / 2 - (viewStart + (viewEnd - viewStart) / 2)
        }

        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
            return 100f / displayMetrics.densityDpi
        }
    }
}